package com.cxc.minio.web;

import com.cxc.minio.common.pojo.CommonResult;
import com.cxc.minio.entity.UserInfo;
import com.cxc.minio.service.UserContractService;
import com.cxc.minio.service.UserImageService;
import com.cxc.minio.service.UserInfoService;
import io.minio.GetObjectArgs;
import io.minio.GetObjectResponse;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.nio.charset.StandardCharsets;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;


@Api(tags = "用户信息接口")
@RestController
@RequestMapping(value = "/api")
@CrossOrigin
@Slf4j
public class UserInfoController {

    @Value("${minio.bucketName}")
    private String bucketName;

    @Resource
    private UserInfoService userInfoService;

    @Autowired
    private MinioClient minioClient;

    @Resource
    private UserImageService userImageService;
    @Resource
    private UserContractService userContractService;

    @ApiOperation("获取用户信息")
    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public CommonResult user(@PathVariable(value = "id") Integer id) throws Exception {
        return CommonResult.success(userInfoService.getUserInfoById(id));
    }

    @ApiOperation("获取用户列表信息")
    @RequestMapping(value = "/users", method = RequestMethod.GET)
    public CommonResult users() throws Exception {
        List<UserInfo> userInfoList = userInfoService.getUserList();
        return CommonResult.success(userInfoList);
    }

    @ApiOperation("上传头像信息")
    @RequestMapping(value = "/user/image", method = RequestMethod.POST)
    public CommonResult image(MultipartFile file,@RequestParam(value = "id") Integer id) throws Exception {
       String subfix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
       String objectName = id+subfix;
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .build());

        boolean b = userImageService.saveOrUpdate(id, bucketName, objectName);


        return CommonResult.success();
    }

    @ApiOperation("上传合同文件")
    @RequestMapping(value = "/user/contract", method = RequestMethod.POST)
    public CommonResult contract(MultipartFile file, @RequestParam(value = "id") Integer id) throws Exception {
        String subfix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String objectName = id+subfix;
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .stream(file.getInputStream(), file.getSize(), -1)

                        .build());
        userContractService.saveOrUpdate(id, bucketName, objectName);

        return CommonResult.success();
    }

    @ApiOperation("用户信息变更")
    @RequestMapping(value = "/user", method = RequestMethod.PUT)
    public CommonResult updateUser( UserInfo userInfo) throws Exception {
        boolean update = userInfoService.updateById(userInfo);
        return update? CommonResult.success(): CommonResult.error();
    }

    @ApiOperation("下载文件内容")
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public CommonResult download(@RequestParam(value = "id") Integer id, HttpServletResponse response) throws Exception {

        UserInfo userInfo = userInfoService.getUserInfoById(id);
        String bucket = userInfo.getUserContractDO().getBucket();
        String object = userInfo.getUserContractDO().getObject();

        //要想让浏览器弹出下载框，你后端要设置一下响应头信息
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" +
                URLEncoder.encode(object, StandardCharsets.UTF_8));
        GetObjectResponse getObjectResponse = minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucket)
                .object(object)
                .build());

        getObjectResponse.transferTo(response.getOutputStream());

        return CommonResult.success();
    }

    @DeleteMapping(value = "/user/{id}")
    public CommonResult delUser(@PathVariable(value = "id") Integer id) {
        try {
            boolean del = userInfoService.delUserById(id);
            return del ? CommonResult.success() : CommonResult.error();
        } catch (Exception e) {
            log.error("删除用户失败：{}",e.getMessage());
            return CommonResult.error();
        }
    }
}
